<?php
namespace app\common\service;

use app\common\model\ZstpSysLog;
use think\Session;

/**
 * 系统日志服务类
 * Class SysLogService
 * @package app\common\service
 */
class SysLogService
{
    /**
     * 添加系统日志
     * @param string $object 操作对象
     * @param int $tableId 操作表的ID
     * @param int $operationType 操作类型 1添加 2修改 3删除 4重试
     * @param string $remarks 操作备注
     * @param array $userInfo 可选的用户信息，如果不提供则自动获取
     * @return bool|int
     */
    public static function addLog($object, $tableId, $operationType, $remarks = '', $userInfo = null)
    {


        // 获取当前登录用户信息
        if ($userInfo === null) {
            $userInfo = self::getCurrentUserInfo();
        }
        
        $userId = isset($userInfo['id']) ? $userInfo['id'] : 0;
        $actor = isset($userInfo['name']) ? $userInfo['name'] : '';
        
        $data = [
            'actor' => $actor,
            'object' => $object,
            'table_id' => $tableId,
            'operation_type' => $operationType,
            'operation_time' => date('Y-m-d H:i:s'),
            'remarks' => $remarks,
            'user_id' => $userId,
            'create_time' => date('Y-m-d H:i:s'),
            'is_deleted' => 0
        ];
        
        try {
            return ZstpSysLog::create($data)->sys_log_id;
        } catch (\Exception $e) {
            // 记录错误日志
            var_dump($e->getMessage());
            \think\Log::error('添加系统日志失败：' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 获取当前登录用户信息
     * 优先从JWT Token中获取，如果没有则尝试从Session中获取
     * @return array 用户信息数组，包含id和name
     */
    public static function getCurrentUserInfo()
    {
        $userInfo = [
            'id' => 0,
            'name' => ''
        ];
        
        // 尝试从请求头中获取token
        $token = isset($_SERVER['HTTP_X_TOKEN']) ? $_SERVER['HTTP_X_TOKEN'] : '';
        
        if (!empty($token)) {
            // 从JWT Token中获取用户信息
            $tokenData = \verifyToken($token);
            if (!empty($tokenData) && isset($tokenData['id'])) {
                $userInfo['id'] = $tokenData['id'];
                $userInfo['name'] = isset($tokenData['name']) ? $tokenData['name'] : '';
                return $userInfo;
            }
        }
        
        // 如果没有从Token获取到信息，则尝试从Session中获取
        $userId = Session::get('user_id');
        $userName = Session::get('user_name');
        if ($userId) {
            $userInfo['id'] = $userId;
            $userInfo['name'] = $userName ?: '';
        }
        
        return $userInfo;
    }
    
    /**
     * 记录添加操作日志
     * @param string $object 操作对象
     * @param int $tableId 操作表的ID
     * @param string $remarks 操作备注
     * @param array $userInfo 可选的用户信息
     * @return bool|int
     */
    public static function addAddLog($object, $tableId, $remarks = '', $userInfo = null)
    {
        return self::addLog($object, $tableId, ZstpSysLog::OPERATION_TYPE_ADD, $remarks, $userInfo);
    }
    
    /**
     * 记录修改操作日志
     * @param string $object 操作对象
     * @param int $tableId 操作表的ID
     * @param string $remarks 操作备注
     * @param array $userInfo 可选的用户信息
     * @return bool|int
     */
    public static function addEditLog($object, $tableId, $remarks = '', $userInfo = null)
    {
        return self::addLog($object, $tableId, ZstpSysLog::OPERATION_TYPE_EDIT, $remarks, $userInfo);
    }
    
    /**
     * 记录删除操作日志
     * @param string $object 操作对象
     * @param int $tableId 操作表的ID
     * @param string $remarks 操作备注
     * @param array $userInfo 可选的用户信息
     * @return bool|int
     */
    public static function addDeleteLog($object, $tableId, $remarks = '', $userInfo = null)
    {
        return self::addLog($object, $tableId, ZstpSysLog::OPERATION_TYPE_DELETE, $remarks, $userInfo);
    }
    
    /**
     * 获取操作类型文本
     * @param int $operationType 操作类型
     * @return string
     */
    public static function getOperationTypeText($operationType)
    {
        switch ($operationType) {
            case ZstpSysLog::OPERATION_TYPE_ADD:
                return '添加';
            case ZstpSysLog::OPERATION_TYPE_EDIT:
                return '修改';
            case ZstpSysLog::OPERATION_TYPE_DELETE:
                return '删除';
            case ZstpSysLog::OPERATION_TYPE_RETRY:
                return '重试';
            case ZstpSysLog::OPERATION_TYPE_AUDIT:
                return '审核';
            default:
                return '未知操作';
        }
    }
    
    /**
     * 查询系统日志列表
     * @param array $where 查询条件
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public static function getLogList($where = [], $page = 1, $limit = 10)
    {
        $count = ZstpSysLog::where($where)->count();
        $list = ZstpSysLog::where($where)
            ->order('operation_time desc')
            ->page($page, $limit)
            ->select();
            
        // 格式化数据
        foreach ($list as &$item) {
            $item['operation_type_text'] = self::getOperationTypeText($item['operation_type']);
        }
        
        return [
            'total' => $count,
            'list' => $list
        ];
    }
} 